<template>
    <div id="add-edit-WaitCheck">
        <el-dialog
            title="登记验收结果"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-divider content-position="left">基础数据</el-divider>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="验收时间" prop="d_AcceptanceTime">
                            <el-date-picker
                                v-model="ruleForm.d_AcceptanceTime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="验收结果">
                            <el-select 
                                class="m-2" 
                                placeholder="请选择验收结果" 
                                v-model="ruleForm.n_AcceptanceState"
                            >
                                <el-option
                                    v-for="item in resultOption"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="验收意见" prop="v_AcceptanceOpinion">
                            <el-input type="textarea" v-model="ruleForm.v_AcceptanceOpinion" placeholder="请输入验收意见" clearable />
                        </el-form-item>
                    </el-col>
                    <el-divider content-position="left">电子签名</el-divider>
                    <div style="padding: 0 20px;width: 100%;">
                        <el-button @click="signHandle" icon="ele-Plus" type="primary" size="small"> 签名 </el-button>
                    </div>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
        <ESignature
            ref="signRef"
            :isSignDialog="isSignDialog"
            @cancelSignClick="cancelSignClick"
            @controlSignClick="controlSignClick"
        ></ESignature>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { 
    FormInstance, 
    FormRules, 
    ElButton, 
    ElCol, 
    ElDialog, 
    ElDivider, 
    ElForm, 
    ElFormItem, 
    ElOption, 
    ElRow, 
    ElSelect,
    ElMessage,
} from 'element-plus';
import { sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';
import FileView from '../file-view.vue';
import ESignature from './e-signature.vue';
import { SMSHDRectifyAcceptanceResult } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id: Number, // 记录id
    d_AcceptanceTime: String, // 验收时间
    n_AcceptanceState: Number, // 验收结果
    v_AcceptanceOpinion: String, // 复查意见
}
export default defineComponent( {
    name: 'add-edit-WaitCheck',
    components: {FileView , ESignature},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
    },
    setup(props,ctx){
        const ruleFormRef = ref();
        const fileRef = ref();
        const isSignDialog = ref(false);
        const signRef = ref(null);
        let base64Signa: any;

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            d_AcceptanceTime: [
				{ required: true, message: '请选择验收日期', trigger: 'change' },
			],
            v_AcceptanceOpinion: [
				{ required: true, message: '请输入验收意见', trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick()
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    state.repeatDis = true;
                    let item = state.ruleForm;
                    uploadFun(item);
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** base64文件转换 */
        const base64Fun = (val: any) => {
            // 从 Base64 字符串中提取实际的 Base64 数据（即逗号后的部分）
            const base64Data = val.split(",")[1];
            // 将 Base64 数据解码为二进制数据
            const binaryString = atob(base64Data);
            // 创建一个 Uint8Array 来存储二进制数据
            const byteArray = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                byteArray[i] = binaryString.charCodeAt(i);
            }
            // 创建 Blob 对象
            const blob = new Blob([byteArray], { type: "image/png" });
            // 创建一个文件对象，将 Blob 对象转换为文件
            const file = new File([blob], "image.png", { type: "image/png" });
            return file;
        }

        /*** 上传电子签名 */
        const uploadFun = async(val: any) => {
            if(base64Signa){
                let setArr = [];
                let res: any;
                setArr.push(base64Fun(base64Signa));
                let param: any = {};
                param.files = setArr;
                param.sourceId = JSON.parse(props.repairInfo).l_AcceptanceSignatureId;
                param.sourceType = 10;
                try{
                    res = await SMSHDRectifyAcceptanceResult(val);
                    if(res.success){
                        try{
                            let rcs: any = await sysFileInfoMultipleUpload(param);
                            if(rcs.success){
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                                ctx.emit('updateData');
                            }else{
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                            }
                        }catch(error){ state.repeatDis = false; }
                    }else{
                        state.repeatDis = false; 
                    }
                }catch(error){ state.repeatDis = false; }
            }else{
                ElMessage({
                    type: 'warning',
                    message: '请完成电子签名',
                    duration: 1000
                });
            }
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                console.log(JSON.parse(props.repairInfo).l_AcceptanceSignatureId,'repairInfo')
                state.ruleForm = {
                    id: JSON.parse(props.repairInfo).id, // 整改记录id
                    d_AcceptanceTime: '', // 验收时间
                    n_AcceptanceState: 0, // 验收结果
                    v_AcceptanceOpinion: '', // 复查意见
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** 电子签名点击事件 */
        const signHandle = () => {
            console.log('电子签名')
            isSignDialog.value = true;
        }

        /*** 电子签名取消事件 */
        const cancelSignClick = () => {
            isSignDialog.value = false;
        }

        /*** 电子签名提交事件 */
        const controlSignClick = (val: any) => {
            base64Signa = val;
            isSignDialog.value = false;
            state.repeatDis = false;
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            ...toRefs(state),
            isUseDialog,
            resultOption: [
                {id: 0, label: '同意验收', value: 0},
                {id: 1, label: '不同意验收', value: 1},
            ],
            rules,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            fileRef,
            signHandle,
            isSignDialog,
            signRef,
            cancelSignClick,
            controlSignClick,
        }
    },
} )
</script>
<style scoped lang="scss">
#file-view{
    width: 100%;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>